package com.hg.design;

import org.springframework.lang.NonNull;

import java.util.Collection;
import java.util.LinkedList;

public class MaxSizeLinkedList extends LinkedList {

    private final long mMaxSize;

    public MaxSizeLinkedList(long mMaxSize) {
        this.mMaxSize = mMaxSize;
    }

    @Override
    public synchronized boolean add(Object o) {
        if (size() == mMaxSize) {//大于最大长度时，移除第一个
            removeFirst();
        }
        return super.add(o);
    }

    @Override
    public synchronized Object removeFirst() {
        return super.removeFirst();
    }

    @Override
    public synchronized boolean addAll(@NonNull Collection c) {
        Object[] objects = c.toArray();
        for (Object o : objects) {
            add(o);
        }
        return size() == mMaxSize;
    }

    @Deprecated
    @Override
    public synchronized void add(int index, Object element) {
        //可自定义逻辑
    }

    @Deprecated
    @Override
    public synchronized boolean addAll(int index, @NonNull Collection c) {
        //可自定义逻辑
        return false;
    }
}
